/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gui.obecnosci;

import db.models.Obecnosc;
import db.models.Student;
import db.models.Termin;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//org.gui.obecnosci//PresenceTable//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "PresenceTableTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "org.gui.obecnosci.PresenceTableTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_PresenceTableAction",
        preferredID = "PresenceTableTopComponent"
)
@Messages({
    "CTL_PresenceTableAction=PresenceTable",
    "CTL_PresenceTableTopComponent=PresenceTable Window",
    "HINT_PresenceTableTopComponent=This is a PresenceTable window"
})
public final class PresenceTableTopComponent extends TopComponent {
    
    private List<Student> students = new ArrayList<Student>();
    private int idTerminu = 0;
    private List<String> dates = new ArrayList<String>();
    
    public PresenceTableTopComponent() {
        initComponents();
        setName(Bundle.CTL_PresenceTableTopComponent());
        setToolTipText(Bundle.HINT_PresenceTableTopComponent());

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        presenceTable = new javax.swing.JTable();
        titleLabel = new javax.swing.JLabel();

        setLayout(new java.awt.BorderLayout());

        presenceTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        presenceTable.setColumnSelectionAllowed(true);
        presenceTable.getTableHeader().setReorderingAllowed(false);
        presenceTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                presenceTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(presenceTable);
        presenceTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

        titleLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(titleLabel, org.openide.util.NbBundle.getMessage(PresenceTableTopComponent.class, "PresenceTableTopComponent.titleLabel.text")); // NOI18N
        titleLabel.setPreferredSize(new java.awt.Dimension(50, 40));
        add(titleLabel, java.awt.BorderLayout.PAGE_START);
    }// </editor-fold>//GEN-END:initComponents

    private void presenceTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_presenceTableMouseClicked
        // TODO add your handling code here:
        if(presenceTable.getSelectedColumn() > 0){
            String data = presenceTable.getColumnName(presenceTable.getSelectedColumn());
            Obecnosc.check(students.get(presenceTable.getSelectedRow()),idTerminu,data,(Boolean)presenceTable.getModel().getValueAt(presenceTable.getSelectedRow(), presenceTable.getSelectedColumn()));
        }
    }//GEN-LAST:event_presenceTableMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable presenceTable;
    private javax.swing.JLabel titleLabel;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        if(titleLabel.getText().equals("jLabel1")) this.close();
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }
    
    private boolean znajdzObecnosc(List<Obecnosc> obecnosci, String data, Student s){
        for(Obecnosc o: obecnosci){
            if(o.getData().equals(data) && o.getStudent().getId()==s.getId()) return o.getObecnosc();
        }
        return false;
    }
    
    public List<String> getDates(){
        return dates;
    }
    
    private void setTable(Termin term){
        idTerminu = term.getId();
        students = Student.getByGroup(term.getGrupa().getId());
        
        DateFormat format = new SimpleDateFormat("dd.MM.yy");
        Calendar cal = Calendar.getInstance();
        String today = format.format(cal.getTime()); // dzisiejsza data
        //sprawdz czy juz są daty dzisiejsze w bazie
        if(isDatesOnDatabase(today,term) == false){
            for(Student s: students){
                Obecnosc.addObecnosc(term, s, today, false);
            }
        }
        //tu tworzenie modelu
        DefaultTableModel model = new DefaultTableModel(){
            @Override
            public Class<?> getColumnClass(int columnIndex) {
               if (columnIndex != 0) {
                  return Boolean.class;
               }
               return super.getColumnClass(columnIndex);
            }
        };// to sie robi zeby byly checkboxy 
        
        while(model.getRowCount() > 0) model.removeRow(0);
        
        model.addColumn("Student");
        List<Obecnosc> obecnosci = Obecnosc.getObecnosci(term);
        dates = new ArrayList<String>();
        String first_date = null;
        if(!obecnosci.isEmpty()){
            first_date = obecnosci.get(0).getData();
            dates.add(first_date);
        }
        for(Obecnosc o: obecnosci){
            if(!o.getData().equals(first_date)){
                first_date = o.getData();
                dates.add(first_date);
            }
        }
        sort(dates);
        //w dates mamy kolejne daty dla terminu, czyli kolejne kolumny
        for(String d: dates){
            model.addColumn(d);
        }

        jScrollPane1.setViewportView(presenceTable);
        //teraz uzupełnianie tabeli
        for(Student s: students){
            Object[] values = new Object[dates.size()+1];
            values[0] = s.getImie()+ " " + s.getNazwisko();
            
            for(int i=1;i<dates.size()+1;i++){
                values[i] = znajdzObecnosc(obecnosci,dates.get(i-1),s);
            }
            model.addRow(values);
        }
        
        presenceTable.setModel(model);
    }
    
    public void setTerm(Termin term){
        setDisplayName(term.getGrupa().getNazwa()+" - "+term.getGrupa().getPrzedmiot().getNazwa()+" - Obecności");
        this.titleLabel.setHorizontalAlignment( SwingConstants.CENTER ); 
        this.titleLabel.setText("Tabela obecności dla: "+term.getGrupa().getNazwa()+" - "+term.getGrupa().getPrzedmiot().getNazwa()+" - "+term.getGodzina_start()+"-"+term.getGodzina_stop());
        setTable(term);
    }
    
    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    private boolean isDatesOnDatabase(String today, Termin termin) {
        return Obecnosc.isThisDateOnDB(today,termin);
    }

    private void sort(List<String> dates) {
        for(String i:dates){
            for(String j:dates){
                int iD = Integer.parseInt(i.substring(0, 2));
                int iM = Integer.parseInt(i.substring(3, 5));
                int iY = Integer.parseInt(i.substring(6, 8));
                int jD = Integer.parseInt(j.substring(0, 2));
                int jM = Integer.parseInt(j.substring(3, 5));
                int jY = Integer.parseInt(j.substring(6, 8));
                if(iY < jY || (iY == jY && iM < jM) || (iY == jY && iM==jM && iD < jD)){
                    //zamieniamy i z j
                    String temp = i;
                    i = j;
                    j = temp;
                }               
            }
        }
    }

    public int getTermId() {
        return this.idTerminu;
    }
}

class TestCellRenderer extends DefaultTableCellRenderer{ }